import React, {useEffect, useState} from "react";
import {Button, notification, Space, Table} from "antd";
import {Link} from "react-router-dom";
import axios from "axios";

const roleObj= {
    "1": "superAdmin",
    "2": "admin",
    "3": "editor"
};

// 注意：这个页面只有管理员和超级管理员才有权限访问
export default function AuditNews() {
    const [dataSource, setDataSource] = useState([]);

    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render: (title, record)=>{
                // return <a href={"#/news-manage/preview/" + record.id}>{title}</a>
                return <Link to={"/news-manage/preview/" + record.id}>{title}</Link>
            }
        },
        {
            title: '作者',
            dataIndex: 'author'
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render: (category)=>category.title
        },
        {
            title: '操作',
            key: 'operation',
            render: (record) => {
                return (
                    <Space size="middle">
                        <Button type="primary" onClick={()=>handleAudit(record,2 )}>通过</Button>
                        <Button danger onClick={()=>handleAudit(record, 3)}>驳回</Button>
                    </Space>
                )
            },
        },
    ];

    const { roleId, region, username } = JSON.parse(localStorage.getItem('token'));
    useEffect(()=>{
        axios.get(`/api/news?auditState=1&_expand=category`).then(response=>{
            // console.log(response.data);
            const data= response.data;
            setDataSource(roleObj[roleId]==="superAdmin" ? data : [
                ...data.filter(item=>{
                    // 自己 或 同区域下角色为编辑
                    if(item.author===username || (item.region===region && roleObj[item.roleId]==="editor")) {
                        return true;
                    }
                    return false;
                })
            ]);
        });
    }, [roleId, region, username]);


    const handleAudit= (item, auditState)=>{
        setDataSource(dataSource.filter(data=>data.id!==item.id));
        axios.patch(`/api/news/${item.id}`, {
            auditState
        }).then(response=>{
            notification.info({
                message: `通知`,
                description: `${item.title}这篇新闻${auditState===2 ? '已审核通过' : '审核未通过'}`,
                placement: 'bottomRight',
            });
        })
    }



    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{ pageSize: 5 }} rowKey={ item=>item.id }/>
        </div>
    );
}
